package com.gaoyi.basemodule.baseUtil;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class GsonUtil {
    private static volatile GsonUtil INSTANCE;
    private Gson mGson;

    public GsonUtil() {
        if (mGson == null) {
            mGson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd HH:mm:ss")
                    .create();
        }
    }

    public static GsonUtil getInstance() {
        if (INSTANCE == null) {
            synchronized (GsonUtil.class) {
                if (INSTANCE == null) {
                    INSTANCE = new GsonUtil();
                }
            }
        }
        return INSTANCE;
    }

    public String toJson(Object obj) {
        return mGson
                .toJson(obj, Object.class);
    }

    public String toJsonToZero(Object obj) {
        Map<String, Object> map = new HashMap<>();
        map.put("0", obj);
        return mGson.toJson(map);
    }

    public Object fromJson(String json, Type typeofT) {
        return mGson.fromJson(json, typeofT);
    }
}
